#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>

int main()
{
  pid_t id = fork();
  if(id == 0){
    printf("I am a process!\n");
    sleep(3);
    //execl("/usr/bin/ls","ls","-a","-i","-l",NULL);
    //execl("/usr/bin/top","top",NULL);
    //execlp("ls","ls","-a","-i","-l",NULL);
    char* myargv[] = {
      "ls",
      "-a",
      "-i",
      "-l",
      NULL
    };
    char* myenv[] = {
      "MYENV=youcanseemeHAHA",
      NULL
    };
    //execv("/usr/bin/ls",myargv);
    //execvp("ls",myargv);
    //execl("./cmd","cmd");
    execle("./cmd","cmd",NULL,myenv);
    //execl("./test.sh","test.sh");
    //execl("./test.py","test.py");
    //execl("./mytest","mytest");
    exit(1);
  }

  int status = 0;
  pid_t ret = waitpid(id, &status, 0);
  if(ret > 0){
    printf("signal: %d\n",status & 0x7F);
    printf("exit code: %d\n",(status>>8) & 0xFF);
  }

  //pid_t id = fork();
  //if(id == 0)
  //{
  //  //child
  //  int count = 0;
  //  while(count<10){
  //    printf("I am child, pid: %d, ppid: %d\n",getpid(), getppid());
  //    sleep(3);
  //    count++;
  //  }
  //  exit(1);
  //}
  //while(1){
  //  int status = 0;
  //  pid_t ret = waitpid(id, &status, WNOHANG);
  //  if(ret > 0){
  //    printf("wait success!\n");
  //    printf("exit code: %d\n",WEXITSTATUS(status));
  //    break;
  //  }
  //  else if(ret == 0)
  //  {
  //    //child not quit,waitpid success
  //    printf("father do other things!\n");
  //    sleep(1);
  //  }
  //  else{
  //    printf("waitpid error!\n");
  //    break;
  //  }
  //}
  return 0;
}
